'use strict';
angular.module('nec-admin.login')
    .controller('loginController', ['$scope', '$state', 'loginService', 'authService', 'userService', 'toast',
        function ($scope, $state, loginService, authService, userService, toast) {
            //登录的函数
            $scope.submit = function () {
                //验证是否输入了用户名和密码
                if (typeof $scope.username === 'undefined' || $scope.username.length === 0) {
                    toast.error('请输入用户名');
                    return;
                }

                if (typeof $scope.password === 'undefined' || $scope.password.length === 0) {
                    toast.error('请输入密码');
                    return;
                }

                //验证用户名是否合法
                var usernameCheckPattern = /[a-zA-Z\_][0-9a-zA-Z\_]*/g;
                if(!usernameCheckPattern.test($scope.username)){
                    toast.error('用户名不正确, 用户名应该为字母开头, 字母数字和下划线组成');
                    angular.element('#username').focus();
                    return;
                }
                console.log($scope.username, $scope.password);
                //向后台发送登录请求
                loginService.login($scope.username, $scope.password).then(function (data) {
                    console.log(data);
                    //检查返回的权限是否为平台管理员
                    if (data.authorities && data.authorities[0] && data.authorities[0].authority &&
                        data.authorities[0].authority === 'ADMIN') {
                        userService.initUserInfo(data.userId, $scope.username);
                        authService.authenticate($scope.username, $scope.password);
                        $state.go('admin.hello');
                    }else  if (data.authorities && data.authorities[0] && data.authorities[0].authority &&
                        data.authorities[0].authority === 'TEACHER') {
                        userService.initUserInfo(data.userId, $scope.username);
                        authService.authenticate($scope.username, $scope.password);
                        $state.go('teacher.hello');
                    }
                    else  if (data.authorities && data.authorities[0] && data.authorities[0].authority &&
                        data.authorities[0].authority === 'STUDENT') {
                        userService.initUserInfo(data.userId, $scope.username);
                        authService.authenticate($scope.username, $scope.password);
                        $state.go('student.hello');
                    }
                    else {
                        $scope.loginError = true;
                        $scope.password = '';
                        toast.error('网络错误, 登录失败');
                    }
                }, function () {
                    $scope.loginError = true;
                    $scope.password = '';
                    toast.error('用户名或密码错误, 请重新登录');
                });
            };
        }]);
